package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.context.BaseContext;
import com.hmall.common.feign.ItemClient;
import com.hmall.common.feign.UserClient;
import com.hmall.common.pojo.Address;
import com.hmall.common.pojo.Item;
import com.hmall.order.dto.OrderDTO;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderLogisticsMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private UserClient userClient;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderLogisticsMapper orderLogisticsMapper;
    @Override
    public Long generateOrders(OrderDTO orderDTO) {
        Order order = new Order();
        Item item = itemClient.findItemById(orderDTO.getItemId());
        Long price = item.getPrice();
        Long num = orderDTO.getNum();
        Long totalPrice = price * num;
        // 总价
        order.setTotalFee(totalPrice);
        // 未支付
        order.setStatus(1);
        order.setPaymentType(Math.toIntExact(orderDTO.getPaymentType()));
        order.setUserId(BaseContext.getUserId());
        orderMapper.insert(order);
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setName(item.getName());
        orderDetail.setOrderId(order.getId());
        orderDetail.setItemId(orderDTO.getItemId());
        orderDetail.setNum(Math.toIntExact(orderDTO.getNum()));
        orderDetail.setSpec(item.getSpec());
        orderDetail.setPrice(totalPrice);
        orderDetail.setImage(item.getImage());
        orderDetailMapper.insert(orderDetail);
        Address addressById = userClient.findAddressById(orderDTO.getAddressId());
        OrderLogistics orderLogistics = new OrderLogistics();
        orderLogistics.setProvince(addressById.getProvince());
        orderLogistics.setCity(addressById.getCity());
        orderLogistics.setTown(addressById.getTown());
        orderLogistics.setStreet(addressById.getStreet());
        orderLogistics.setOrderId(order.getId());
        orderLogistics.setContact(addressById.getContact());
        orderLogistics.setPhone(addressById.getMobile());
        orderLogisticsMapper.insert(orderLogistics);
        itemClient.updateStock(orderDTO.getItemId(), Math.toIntExact(orderDTO.getNum()));
        return order.getId();
    }
}
